package cn.xiaopengstack.trigger.job;

import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import cn.xiaopengstack.domain.award.repository.IRaffleAwardRepository;
import cn.xiaopengstack.domain.task.model.TaskEntity;
import cn.xiaopengstack.domain.task.repository.ITaskRepository;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author jiangyangang
 */
@Component
@Slf4j
public class ResendMqFromAwardTaskJob {

    @Resource
    private IRaffleAwardRepository raffleAwardRepository;

    @Resource
    private ITaskRepository taskRepository;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private IDBRouterStrategy dbRouter;


    @XxlJob("ResendMqTaskJob")
    public void execute(){
        int dbCount = dbRouter.dbCount();
        for (int dbIndex = 1; dbIndex <= dbCount ; dbIndex++) {
            List<TaskEntity> taskEntities = taskRepository.queryFailedTask(dbIndex);
            for (TaskEntity taskEntity : taskEntities) {
                // 使用线程池执行
                threadPoolExecutor.execute(() -> {
                    try {
                        taskRepository.sendTaskMq(taskEntity);
                        taskRepository.updateTaskSendMessageCompleted(taskEntity);
                    } catch (Exception e) {
                        log.error("task发送奖品MQ失败, {}, {}", taskEntity.getTopic(), taskEntity.getUser().getUserId());
                        taskRepository.updateTaskSendMessageFail(taskEntity);
                    }
                });

            }
        }
    }

}
